import SnakeCtrl from "../../ctrl/SnakeCtrl";

const { ccclass, property } = cc._decorator;

@ccclass
export default class UIRocker extends cc.Component {

    activated = false
    maxr = 32;

    start() {
        let that = this
        let node = this.node
        let point = this.node.children[0]

        /** 控制摇杆 */
        function control(e) {
            //设置为激活状态
            that.activated = true
            let wpos = e.getLocation()
            let pos = node.convertToNodeSpaceAR(wpos);
            let len = pos.mag();//获取向量长度
            if (len > that.maxr) {
                pos.x = that.maxr * pos.x / len;
                pos.y = that.maxr * pos.y / len;
            }
            point.setPosition(pos);
            //目标角度
            let ang = Math.atan2(pos.y, pos.x) * 180 / Math.PI
            SnakeCtrl.ins.ctrlTurn(ang)
        }

        /** 结束控制 */
        function done() {
            that.activated = false
            point.setPosition(cc.v2(0, 0));
        }

        node.on(cc.Node.EventType.TOUCH_START, control, this);
        node.on(cc.Node.EventType.TOUCH_MOVE, control, this);
        node.on(cc.Node.EventType.TOUCH_END, done, this);
        node.on(cc.Node.EventType.TOUCH_CANCEL, done, this);

    }
}
